package ping.download;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import ping.utils.FileUtils;

public class HttpDownloader {
	public String download(String urlStr){
		StringBuffer sb = new StringBuffer();
		String line = null;
		BufferedReader buffer = null;
		try{
			URL url = new URL(urlStr);
			HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
			buffer = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
			while((line=buffer.readLine()) != null){
				sb.append(line);
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try{
				buffer.close();
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		return sb.toString();
	}
	//return 0 is succesfful.. -1 is failed.
	public int downFile(String webUrl, String path, String fileName) {
		// TODO Auto-generated method stub
		InputStream input = null;
		try{
			FileUtils fileUtils = new FileUtils();
			if( fileUtils.isFileExist(fileName, path)){
				return 1;
			}else {
				input = getInputStreamfromUrl(webUrl);
				File resultFile = fileUtils.write2SDFromInput(path, fileName, input);
				if(resultFile == null){
					return -1;
				}
			}
			
		}catch(Exception e){
			e.printStackTrace();
		}
		return 0;
	}
	private InputStream getInputStreamfromUrl(String webUrl) 
	       throws MalformedURLException, IOException   {
		// TODO Auto-generated method stub
		URL url = new URL(webUrl);
		HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
		InputStream input = urlConn.getInputStream();
		return input;
	}
}
